<template>
  <a-card class="general-card" title="商品分类" :bordered="false">
    <a-row style="margin-bottom: 16px">
      <a-col :span="16">
        <a-space>
          <a-button type="primary" @click="addParent">
            添加一级分类
          </a-button>
        </a-space>
      </a-col> 
    </a-row>
    <PickTablePage
      ref="tablePageRef"
      :columns="columnsTable"
      :methods="sortMethods"
      :bordered="true"
      :dataList = "labelData"
      :enablePagination="false"
      :checkbox="isNormal ? false : true"
      :radio="isNormal ? false : true"
      @selectTableChange="chosenCategory"
    >
      <template #children="{ data }">
        {{ data.name }}
      </template>
      <template #commissionRate="{ data }">
        {{ data.commissionRate || 0 }}%
      </template>
      <template #addSonClass="{ data }" >
          <a-button type='text' v-if="data.level != 2" @click="detailChildCategory(data)">添加子分类</a-button>
      </template>
      <template #binding="{ data }">
        <a-dropdown v-if="data.level == 2" :popup-max-height="false">
          <a-button type="text" status="warning">绑定<icon-down /></a-button>
          <template #content>
            <a-doption @click="brandOperation(data)">编辑绑定品牌</a-doption>
            <a-doption @click="specOperation(data)">编辑绑定规格</a-doption>
            <a-doption @click="parameterOperation(data)"
              >编辑绑定参数</a-doption
            >
          </template>
        </a-dropdown>
      </template>
      <template #operation="{ data }">
        <a-dropdown :popup-max-height="false">
          <a-button type="text" >操作<icon-down /></a-button>
          <template #content>
            <a-doption @click="TbaleDataEdit(data)">编辑</a-doption>
            <a-doption v-if="data.deleteFlag == 1" @click="enable(data)">启用</a-doption>
            <a-doption v-if="data.deleteFlag == 0" @click="disable(data)">禁用</a-doption>
            <a-doption @click="handleDelete(data)">删除</a-doption>
          </template>
        </a-dropdown>
      </template>
    </PickTablePage>
    <classifyModel @refresh="getData" ref="operationModal"></classifyModel>
    <a-modal v-model:visible="modalBrandVisible" :width="500">
      <template #title>品牌关联 </template>
      <a-form :model="brandForm" :style="{ width: '380px' }" auto-label-width>
        <a-select
          v-model="brandForm.categoryBrands"
          :style="{ width: '400px' }"
          multiple
          allow-clear
        >
          <a-option v-for="item in brandWay" :key="item.id" :value="item.id">{{
            item.name
          }}</a-option>
        </a-select>
      </a-form>
      <template #footer>
        <div style="text-align: right">
          <a-button  @click="modalBrandVisible = false" style="margin-right: 5px;"
            >取消</a-button
          >
          <a-button type="primary" @click="SubmitCategoryBrand">提交</a-button>
        </div>
      </template>
    </a-modal>
    <a-modal v-model:visible="modalSpecVisible" :width="500">
      <template #title>规格关联 </template>
      <a-form :model="specForm" :style="{ width: '380px' }" auto-label-width>
        <a-select
          v-model="specForm.categorySpecs"
          :style="{ width: '400px' }"
          multiple
          allow-clear
        >
          <a-option
            v-for="item in specifications"
            :key="item.id"
            :value="item.id"
            >{{ item.specName }}</a-option
          >
        </a-select>
      </a-form>
      <template #footer>
        <div style="text-align: right">
          <a-button  @click="modalSpecVisible = false"  style="margin-right: 5px;"
            >取消</a-button
          >
          <a-button type="primary" @click="submitCategorySpec">提交</a-button>
        </div>
      </template>
    </a-modal>
  </a-card>
</template>

<script setup lang="ts">
  import {
delCategory,
disableCategory,
getAllCategory,
getBrandListData,
getCategoryBrandListData,
getCategorySpecListData,
getSpecificationList,
saveCategoryBrand,
saveCategorySpec
} from '@/api/goods';
import { PickTablePage } from '@pickmall/ui-v3-components'
import { ColumnsDataRule, MethodsRule } from '@/types/global';
import { useRouter } from 'vue-router';

  import useCurrentInstance from '@/hooks/useCurrentInstance';
import { deleteFlagStatus } from '@/utils/tools';
import { Message } from '@arco-design/web-vue';
import { onMounted, ref } from 'vue';
import classifyModel from './module/classifyModel.vue';

  const flatTableList = ref<Array<any>>([]);
  // 组件模式
  const props = defineProps({
    templateModel: {
      type: String,
      default: 'normal',
    },
  })
  const isNormal: boolean = props.templateModel === 'normal';
  const emit = defineEmits(['selectTableChange'])
  const router = useRouter();
  const modalBrandVisible = ref<boolean>(false); // 品牌关联编辑显示
  const modalSpecVisible = ref<boolean>(false); // 品牌关联编辑显示
  const brandForm = ref({
    categoryBrands: [],
  });
  const specForm = ref({
    categorySpecs: [],
  }) as any;
  const specifications = ref([]) as any; // 规格集合
  const categoryId = ref<string>('');
  const tablePageRef = ref<any>('');
  const brandWay = ref([]) as any; // 所有品牌
  //  弹出层是否显示
  const operationModal = ref(null) as any;
  // 获取modal
  const modal = useCurrentInstance().globalProperties?.$modal;
  const labelData = ref<any>([]);

  const getBrandList = async () => {
    const res = await getBrandListData();
    brandWay.value = res.data.result;
  };
  const getSpecList = () => {
    getSpecificationList().then((res: any) => {
      if (res.data.length != 0) {
        specifications.value = res.data.result;
      }
    });
  };
  const columnsTable: ColumnsDataRule[] = [
    {
      title: '分类名称',
      dataIndex: 'name',
      width: 150,
      slot: true,
      slotTemplate: 'children',
    },
    {
      title: '分类状态',
      dataIndex: 'deleteFlag',
      width: 150,
      slot: true,
      slotData: {
        badge: deleteFlagStatus,
      },
    },

    {
      title: '佣金',
      dataIndex: 'commissionRate',
      width: 150,
      slot: true,
      slotTemplate: 'commissionRate',
    },
  ];

  const sortMethods: MethodsRule = {
    title: '操作',
    width: 250,
    fixed: 'right',
    methods: [
      {
        title: '绑定',
        slot: true,
        slotTemplate: 'binding',
      },
      {
        title: '添加子分类',
        slot:true,
        slotTemplate:'addSonClass',
        // callback: 'addSonClass',
      },
      {
        title: '操作',
        slot: true,
        slotTemplate: 'operation',
      },
    ],
  };
  // 获取分类数据
  const getData = () => {
    getAllCategory().then(res => {
      if(res.data.success) {
        if(res.data.result.length){
        const loop = (data:any) => {
          const result:Array<any> = [];
          data.forEach((item:any) => {
            if (item.children && item.children.length) {
              const filterData = loop(item.children);
              result.push({...item, children: filterData});
            } else {
              result.push({...item, children: null});
            }
            flatTableList.value.push(item);
          });
          return result;
        };
        labelData.value = loop(res.data.result) ;
      }
      }
    })
  };

  // 弹框新增/编辑/标题
  const modalOperation = (
    visible: boolean,
    modalTitle: string,
    showParent: boolean,
    modalType?: number
  ) => {
    operationModal.value.visible = visible;
    operationModal.value.modalTitle = modalTitle;
    operationModal.value.showParent = showParent;
    operationModal.value.modalType = modalType;
  };
  // 添加一级分类
  const addParent = () => {
    modalOperation(true, '添加一级分类', true, 0);
    operationModal.value.parentTitle = '顶级分类';
    operationModal.value.formAdd.id = null;
  };
  // 编辑
  const TbaleDataEdit = (row: any) => {
    console.log('编辑', row);
    operationModal.value.formAdd.name = row.name;
    operationModal.value.formAdd.id = row.id;
    operationModal.value.formAdd.level = row.level;
    operationModal.value.formAdd.parentId = row.parentId;
    operationModal.value.formAdd.sortOrder = row.sortOrder;
    operationModal.value.formAdd.commissionRate = row.commissionRate;
    operationModal.value.formAdd.deleteFlag = row.deleteFlag == false ? 0 : 1;
    operationModal.value.formAdd.image = row.image;
    modalOperation(true, '编辑', false, 1);
  };
  // 添加子分类
  const detailChildCategory = (row: any) => {
    operationModal.value.formAdd.id = null;
    operationModal.value.formAdd.image = row.image;
    operationModal.value.parentTitle = row.name;
    // operationModal.value.formAdd.name = row.name;
    operationModal.value.formAdd.name = '';
    operationModal.value.formAdd.level = row.level + 1;
    operationModal.value.formAdd.parentId = row.id;
    operationModal.value.formAdd.commissionRate = row.commissionRate;
    modalOperation(true, '添加子分类', true, 0);
  };
  // 回调删除
  function handleDelete(data: any) {
    modal.confirm({
      title: '确认删除',
      content: `您确认要删除${data.name}?`,
      alignCenter: false,
      onOk: async () => {
        const res = await delCategory(data.id);
        if (res.data.success) {
          Message.success('删除成功！');
          getData()
          tablePageRef.value.init();
        }
      },
    });
  }
  // 启用/禁用
  const startInhibit = (
    row: any,
    title: string,
    content: string,
    parameter: any
  ) => {
    modal.confirm({
      title,
      content: `您是否要${content}当前分类 ${row.name} 及其子分类?`,
      alignCenter: false,
      onOk: async () => {
        const res = await disableCategory(row.id, {
          enableOperations: parameter,
        });
        if (res.data.success) {
          Message.success('操作成功');
          getData()
          tablePageRef.value.init();
        }
      },
    });
  };
  // 禁用
  const disable = (row: any) => {
    startInhibit(row, '确认禁用', '禁用', true);
  };
  // 启用
  const enable = (row: any) => {
    startInhibit(row, '确认启用', '启用', 0);
  };
  // 弹出品牌关联框
  const brandOperation = (v: any) => {
    getCategoryBrandListData(v.id).then((res: any) => {
      categoryId.value = v.id;
      if (res.data.code == 200) {
        brandForm.value.categoryBrands = res.data.result.map(
          (item: any) => item.id
        );
        modalBrandVisible.value = true;
      }
    });
  };
  // 弹出规格关联框
  const specOperation = (v: any) => {
    getCategorySpecListData(v.id).then((res: any) => {
      categoryId.value = v.id;
      specForm.value.categorySpecs = res.data.map((item: any) => item.id);
      modalSpecVisible.value = true;
    });
  };
  // 编辑绑定参数
  const parameterOperation = (v: any) => {
    router.push({ name: 'parameter', query: { id: v.id } });
  };
  // 保存分类品牌绑定
  const SubmitCategoryBrand = () => {
    saveCategoryBrand(categoryId.value, {
      categoryBrands: brandForm.value.categoryBrands.join(','),
    }).then((res) => {
      if (res.data.code == 200) {
        Message.success('操作成功');
        getData()
        modalBrandVisible.value = false;
      }
    });
  };
  // 保存分类规格绑定
  const submitCategorySpec = () => {
    saveCategorySpec(categoryId.value, {
      categorySpecs: specForm.value.categorySpecs.join(','),
    }).then((res: any) => {
      if (res.data.code == 200) {
        Message.success('操作成功');
        getData()
        modalSpecVisible.value = false;

      }
    });
  };
   // 选择商品分类
  function chosenCategory(val: any) {
    const data = flatTableList.value.find((item:any)=> item.id === val[0])
    emit('selectTableChange', { ...data, ___type: 'category' })
  }

  // 初始化
  onMounted(() => {
    getBrandList();
    getSpecList();
    getData();
  });
</script>

